package com.cn.jx.manager.service.mtn.Impl;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cn.jx.common.service.BaseService;
import com.cn.jx.manager.dao.ContactRepository;
import com.cn.jx.manager.dao.JobRepository;
import com.cn.jx.manager.dao.OrgRepository;
import com.cn.jx.manager.dao.PwdRepository;
import com.cn.jx.manager.dao.ResourceRepository;
import com.cn.jx.manager.dao.RoleRepository;
import com.cn.jx.manager.dao.RoleResourceRepository;
import com.cn.jx.manager.dao.UserOrgJobRepository;
import com.cn.jx.manager.dao.UserRepository;
import com.cn.jx.manager.dao.UserRoleRepository;
import com.cn.jx.manager.form.UserForm;
import com.cn.jx.manager.form.UserOrgJobForm;
import com.cn.jx.manager.po.Contact;
import com.cn.jx.manager.po.Pwd;
import com.cn.jx.manager.po.User;
import com.cn.jx.manager.po.UserOrgJob;
import com.cn.jx.manager.po.UserRole;
import com.cn.jx.manager.service.mtn.IUserServiceMtn;
import com.jx.enumType.OperatEnum;
import com.jx.exception.MyException;
import com.jx.util.CodeUtil;
import com.jx.util.DateUtil;
import com.jx.util.MD5;
import com.jx.util.ObjectTransUtil;
import com.jx.util.Utility;

/**
 * <p>UserServiceImpl  用户，员工服务层实现
 * <p>集成<{@link BaseService BaseService}公用服务，实现<{@link IUserService IUserService}接口
 * <p>{@link UserRepository userDao <tt>用户查询dao层</tt>}
 * <p>{@link PwdRepository pwdDao <tt>密码查询dao层</tt>}
 * <p>{@link ContactRepository contactDao <tt>联系人查询dao层</tt>}
 * <p>{@link UserOrgJobRepository userOrgJobDao <tt>用户组织岗位关系查询dao层</tt>}
 * <p>{@link OrgRepository orgDao <tt>组织查询dao层</tt>}
 * <p>{@link JobRepository jobDao <tt>岗位查询dao层</tt>}
 * <p>{@link RoleRepository roleDao <tt>角色查询dao层</tt>}
 * <p>{@link ResourceRepository resourceDao <tt>资源查询dao层</tt>}
 * <p>{@link RoleResourceRepository roleResourceDao <tt>角色资源关系查询dao层</tt>}
 * 
 * @author <h1>jiangxu2  2019年11月21日</h1>
 * @version v1.11.20.2019
 * @since 1.0
 * 
 */
@Service("userServiceMtn") 
@Transactional
public class UserServiceImplMtn extends BaseService implements IUserServiceMtn {
	@Autowired
	private UserRepository userDao;
	
	@Autowired
	private PwdRepository pwdDao;
	
	@Autowired
	private ContactRepository contactDao;
	
	@Autowired
	private UserOrgJobRepository userOrgJobDao;
	
	@Autowired
	private UserRoleRepository userRoleDao;
	
	/* 保存或更新用户信息 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveOrUpdateUser(UserForm item) throws Exception {
		if (Utility.isNotBlank(item.getId())) {
			User userEntry = findEntityByPkid(item.getId(), User.class);
			User uo = ObjectTransUtil.getUpdateObj(userEntry, item);
			if (uo != null) {
				uo.setOperatTime(new Date());
				uo.setOperatUser(item.getOperatUser());
				User res = userDao.save(uo);
				// 删除缓存 更新用户
//				redisUtil.hdelItem("userServiceQry", "findUserByLoginName=" + res.getLoginName());
//				redisUtil.hdelItem("userServiceQry", "getUserById=" + res.getId());

				// 保存日志
				logUtil.LogMsg(User.class, res.getId(), OperatEnum.UPDATE, item.getOperatUser());

			}
		} else {
			// 联系方式
			Contact ctact = Contact.getInstance(item.getOperatUser());
			ctact.setMobile(item.getMobile());
			ctact.setEmail(item.getEmail());
			ctact.setAreaCode(item.getAreaCode());
			ctact.setCountryCode(item.getCountryCode());
			Contact contactEntry = contactDao.save(ctact);

			Date today = new Date();
			int ct = userDao.findRegistUserNumToday(DateUtil.getStartTime(today), DateUtil.getEndTime(today));
			// 创建用户信息
			User user = User.getInstance(item.getOperatUser());
			user.setLoginName(item.getLoginName());
			user.setEmployeeCode(CodeUtil.getEmployeeCode(ct));
			user.setChineseName(item.getChineseName());
			user.setEnglishName(item.getEnglishName());
			user.setAdminFlg(item.getAdminFlg() == null ? 0 : item.getAdminFlg());
			user.setSex(item.getSex());
			user.setEmployeeType(item.getEmployeeType());
			user.setJobLevel(item.getJobLevel());
			user.setContactId(contactEntry.getId());
			User u = userDao.save(user);

			// 保存用户组织关系
			UserOrgJob uuoj = UserOrgJob.getInstance();
			uuoj.setUserId(u.getId());
			uuoj.setOrgId(item.getOrgId());
			uuoj.setJobId(item.getJobId());
			uuoj.setMajor(1);
			userOrgJobDao.save(uuoj);

			// 创建密码信息
			Pwd pwd = Pwd.getInstance();
			pwd.setPassword(MD5.md52(item.getPassword()));
			pwd.setUserId(u.getId());
			pwdDao.save(pwd);

			// 保存日志
			logUtil.LogMsg(User.class, u.getId(), OperatEnum.SAVE, item.getOperatUser());
			
			//发送站内信
			String conten=MessageFormat.format("欢迎{0}同事今日入职我们部门，大家以后多多帮助！", u.getChineseName());
			messUtil.sendEmailMsgByOrgSign("人事部", item.getOrgId(), "新人入职", conten, item.getOperatUser());
		}
	}
	
	/* 保存密码 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public Pwd savePassword(Pwd item) throws Exception {
		return pwdDao.save(item);
	}
	
	/* 删除用户 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void delUser(List<String> ids, String operator) throws Exception {
		// 第一步 删除用户组织岗位的关系表
		userOrgJobDao.deleteRealationByUserIds(ids);
		// 第二步删除用户角色关系
		userRoleDao.deleteRealationByUserIds(ids);
		// 删除用户
		deleteEntityByIds(ids, User.class);// 标记删除可找回 所以关系表暂时不删
		// 保存日志
		logUtil.LogMsg(User.class, Utility.getListToStr(ids), OperatEnum.DELETE, operator);
	}

	/* 删除用户 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void removeUser(List<String> ids, String operator) throws Exception {
		//彻底移除不可找回
		removeEntityByIds(ids,User.class);
		logUtil.LogMsg(User.class, Utility.getListToStr(ids), OperatEnum.REMOVE, operator);
	}
	
	/* 恢复用户 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void recoverUser(List<String> ids, String operator) throws Exception {
		recoverEntityById(ids,User.class);
		logUtil.LogMsg(User.class, Utility.getListToStr(ids), OperatEnum.RECOVER, operator);
	}

	/* 清空 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void removeUserAll(String opertor) throws Exception {
		removeAllEntity(User.class);
		// 保存日志
		logUtil.LogMsg(User.class, "ALL", OperatEnum.REMOVE, opertor);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void allotOrgJobByUser(UserOrgJobForm uoj) throws Exception {
		//第一步 判断是否选择主岗
		if(uoj.getMajor()!=null && uoj.getMajor()==1){
			userOrgJobDao.updateUOJmajorRemove(uoj.getUserId());//一个人只能有一个主岗
		}
		UserOrgJob uojent=UserOrgJob.getInstance();
		uojent.setUserId(uoj.getUserId());
		uojent.setJobId(uoj.getJobId());
		uojent.setOrgId(uoj.getOrgId());
		uojent.setMajor(uoj.getMajor());
		UserOrgJob u=userOrgJobDao.save(uojent);
		
		// 保存日志
		logUtil.LogMsg(User.class, u.getId(), OperatEnum.USER_ALLOT_OJ, uoj.getOperatUser());
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void setMajorByuoj(String userid, String orgid, String jobid, String opertor) throws Exception {
		//先取消设置主岗
		userOrgJobDao.updateUOJmajorRemove(userid);
		
		//设置
		userOrgJobDao.updateUOJmajorSet(orgid, userid, jobid);
		
		// 保存日志
		logUtil.LogMsg(User.class, userid+"_"+orgid+"_"+jobid, OperatEnum.USER_SET_MJOR, opertor);
	}

	@Override
	public void delUOJbyids(List<String> ids, String opertor) throws Exception {
		removeEntityByIds(ids,UserOrgJob.class);
		// 保存日志
		logUtil.LogMsg(UserOrgJob.class, Utility.getListToStr(ids), OperatEnum.USER_DEL_OJ, opertor);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void addUserRole(String userId, String[] roleId, String opertor) throws Exception {
		try {
			// 第一步删除此用户下所有角色
			userRoleDao.deleteRealationByUserId(userId);

			// 第二步分别保存新的资源
			for (String resid : roleId) {// 循环传入的
				UserRole rr = UserRole.getInstance();
				rr.setUserId(userId);
				rr.setRoleId(resid);
				userRoleDao.save(rr);
			}
			// 保存日志
			logUtil.LogMsg(UserRole.class, userId, OperatEnum.ROLE_ALLOT, opertor);
			
		}catch (Exception e) {
			e.printStackTrace();
			throw new MyException(e.getMessage());
		}
	}

}
